import config from './config.js';

if (typeof uni === 'undefined') {
	throw new Error('uni is not defined. Ensure running in UniApp environment.');
}

const request = (options) => {
	return new Promise((resolve, reject) => {
		// 每次请求动态获取最新token
		const token = uni.getStorageSync('token') || '';
		
		
		// 初始化headers
		options.header = options.header || {};
		options.header.Authorization = token ? `${token}` : '';

		const baseUrl = config.baseUrl || 'http://localhost:8080';
		options = {
			...options,
			url: baseUrl + options.url,
			timeout: options.timeout || config.timeout || 30000,
			method: options.method || 'GET',
			header: options.header,
			data: options.data || {}
		};
		
		// 重构POST请求处理逻辑
		if (options.method.toUpperCase() === 'POST') {
			if (options.isFormData) {
				// 使用URLSearchParams处理form-data格式
				const params = new URLSearchParams();
				for (const key in options.data) {
					params.append(key, options.data[key]);
				}
				options.data = params.toString();

				// 设置正确的Content-Type
				options.header['Content-Type'] = 'application/x-www-form-urlencoded';
			
			} else {
				// JSON格式处理
				options.header['Content-Type'] = 'application/json';
				if (options.data && typeof options.data === 'object') {
					options.data = JSON.stringify(options.data);
				}
			}
		}

		// 请求执行函数
		const executeRequest = (retry = true) => {
			uni.request({
				...options,
				success: async (res) => {
					if (res.statusCode === 200) {
						if (res.data.code === 0) {
							resolve(res.data);
						} else {
							uni.showToast({
								title: res.data.msg || '请求失败',
								icon: 'none'
							});
							reject(res.data);
						}
					} else if (res.statusCode === 401 && retry) {
						try {
							const newToken = await refreshToken();
							options.header.Authorization = `Bearer ${newToken}`;
							uni.setStorageSync('token', newToken);
							executeRequest(false);
						} catch (error) {
							uni.navigateTo({
								url: '/pages/login/login'
							});
							reject(new Error('未授权'));
						}
					} else {
						uni.showToast({
							title: `网络错误: ${res.statusCode}`,
							icon: 'none'
						});
						reject(new Error(`网络错误: ${res.statusCode}`));
					}
				},
				fail: (err) => {
					uni.showToast({
						title: '请求失败',
						icon: 'none'
					});
					reject(err);
				}
			});
		};

		executeRequest();
	});
};

const uploadFile = (url, filePath, formData = {}, options = {}) => {
	return new Promise((resolve, reject) => {
		// 每次上传获取最新token
		const token = uni.getStorageSync('token') || '';

		const baseUrl = config.baseUrl || 'http://localhost:8080';
		uni.uploadFile({
			url: baseUrl + url,
			filePath: filePath,
			name: 'file',
			formData: formData,
			header: {
				...options.header,
				Authorization: token ? `Bearer ${token}` : ''
			},
			success: (res) => {
				if (res.statusCode === 200) {
					const data = JSON.parse(res.data);
					if (data.code === 0) {
						resolve(data);
					} else {
						uni.showToast({
							title: data.msg || '上传失败',
							icon: 'none'
						});
						reject(data);
					}
				} else {
					uni.showToast({
						title: `上传错误: ${res.statusCode}`,
						icon: 'none'
					});
					reject(new Error(`上传错误: ${res.statusCode}`));
				}
			},
			fail: (err) => {
				uni.showToast({
					title: '上传失败',
					icon: 'none'
				});
				reject(err);
			}
		});
	});
};

const refreshToken = () => {
	return new Promise((resolve, reject) => {
		const refreshToken = uni.getStorageSync('refreshToken') || '';
		if (!refreshToken) {
			reject(new Error('No refresh token'));
			return;
		}

		const baseUrl = config.baseUrl || 'http://localhost:8080';

		uni.request({
			url: baseUrl + '/auth/refresh',
			method: 'POST',
			header: {
				'Content-Type': 'application/json',
				Authorization: `Bearer ${refreshToken}`
			},
			success: (res) => {
				if (res.statusCode === 200 && res.data.code === 0) {
					const newToken = res.data.data.accessToken;
					uni.setStorageSync('token', newToken);
					if (res.data.data.refreshToken) {
						uni.setStorageSync('refreshToken', res.data.data.refreshToken);
					}
					resolve(newToken);
				} else {
					uni.showToast({
						title: 'Token刷新失败',
						icon: 'none'
					});
					reject(new Error('Failed to refresh token'));
				}
			},
			fail: (err) => {
				uni.showToast({
					title: 'Token刷新请求失败',
					icon: 'none'
				});
				reject(err);
			}
		});
	});
};

const http = {
	get(url, data = {}, options = {}) {
		return request({
			url,
			data,
			method: 'GET',
			...options
		});
	},
	post(url, data = {}, options = {}) {
		return request({
			url,
			data,
			method: 'POST',
			...options
		});
	},
	put(url, data = {}, options = {}) {
		return request({
			url,
			data,
			method: 'PUT',
			...options
		});
	},
	delete(url, data = {}, options = {}) {
		return request({
			url,
			data,
			method: 'DELETE',
			...options
		});
	},
	upload(url, filePath, formData = {}, options = {}) {
		return uploadFile(url, filePath, formData, options);
	}
};

export default http;